package gold.digger;

import gold.utils.InputUtil;
import gold.utils.UF;

import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC886 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public boolean possibleBipartition(int n, int[][] dislikes) {
            if (n <= 2 || dislikes.length <= 0) return true;

            UF uf = new UF(n + 1);
            Map<Integer, List<Integer>> disGraph = new HashMap<>();

            for (int[] dislike : dislikes) {
                if (!disGraph.containsKey(dislike[0])) disGraph.put(dislike[0], new ArrayList<>());
                if (!disGraph.containsKey(dislike[1])) disGraph.put(dislike[1], new ArrayList<>());
                disGraph.get(dislike[1]).add(dislike[0]);
                disGraph.get(dislike[0]).add(dislike[1]);
            }

            for (Integer node : disGraph.keySet()) {
                for (Integer dis : disGraph.get(node)) {
                    if (uf.connected(node, dis)) return false;
                    else uf.union(dis, disGraph.get(node).get(0));
                }
            }

            return true;
        }
    }

    /**
     * Created by fanzhenyu02 on 2020/6/27.
     * Union Find 算法实现
     */
    public class UF {
        // 连通分量个数
        private int count;
        // 存储一棵树
        private int[] parent;
        // 记录树的“重量”
        private int[] size;

        public UF(int n) {
            this.count = n;
            parent = new int[n];
            size = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                size[i] = 1;
            }
        }

        /* 将 p 和 q 连接 */
        public void union(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            if (rootP == rootQ)
                return;

            // 小树接到大树下面，较平衡
            if (size[rootP] > size[rootQ]) {
                parent[rootQ] = rootP;
                size[rootP] += size[rootQ];
            } else {
                parent[rootP] = rootQ;
                size[rootQ] += size[rootP];
            }
            count--;
        }

        /* 判断 p 和 q 是否连通 */
        public boolean connected(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            return rootP == rootQ;
        }

        private int find(int x) {
            while (parent[x] != x) {
                // 进行路径压缩
                parent[x] = parent[parent[x]];
                x = parent[x];
            }
            return x;
        }

        /* 返回图中有多少个连通分量 */
        public int count() {
            return count;
        }

        /* 返回图中联通集合 */
        public Map<Integer, List<Integer>> outputAggregateSet(int n) {
            Map<Integer, List<Integer>> aggregateMap = new HashMap<>();

            // 共有n个集合
            for (int i = 0; i < n; i++) {
                int parentId = find(i);
                if (!aggregateMap.containsKey(parentId)) aggregateMap.put(parentId, new ArrayList<>());
                aggregateMap.get(parentId).add(i);
            }

            System.out.println(aggregateMap.toString());
            return aggregateMap;
        }
    }

    class Solution_Complex_Thought {
        public boolean possibleBipartition(int n, int[][] dislikes) {
            if (n <= 2 || dislikes.length <= 0) return true;

            UF uf = new UF(n + 1);
            int firstGroup = dislikes[0][0], secondGroup = dislikes[0][1];
            Set<Integer> oneDisLikeSet = new HashSet<>();

            for (int[] dislike : dislikes) {
                if (dislike[0] == firstGroup) {
                    oneDisLikeSet.add(dislike[1]);
                }
                if (dislike[1] == firstGroup) {
                    oneDisLikeSet.add(dislike[0]);
                }
            }

            // 初始化 oneLikeSet, 分化为两大group
            for (int i = 1; i <= n; i++) {
                if (!oneDisLikeSet.contains(i)) {
                    uf.union(firstGroup, i);
                } else {
                    uf.union(secondGroup, i);
                }
            }

            for (int[] dislike : dislikes) {
                if (dislike[0] != firstGroup && dislike[1] != firstGroup) {
                    // 开始判断当前憎恨二人组是否可以归类与当前两大group
                    if (uf.connected(dislike[0], firstGroup) && uf.connected(dislike[1], secondGroup)) continue;
                    if (uf.connected(dislike[0], secondGroup) && uf.connected(dislike[1], firstGroup)) continue;
                    if (uf.connected(dislike[0], firstGroup) && uf.connected(dislike[1], firstGroup)) return false;// notice: this place is wrong thought
                    if (uf.connected(dislike[0], secondGroup) && uf.connected(dislike[1], secondGroup)) return false;
                }
            }

            return true;
        }
    }

    public void run() {
        Solution solution = new Solution();
//        int[][] arr = InputUtil.toDoubleIntegerArray("[[1,2],[2,3],[3,4],[4,5],[1,5]]");
//        输出：false
//        System.out.println(solution.possibleBipartition(5, arr));

//        int[][] arr = InputUtil.toDoubleIntegerArray("[[1,2],[1,3],[2,4]]");
//        System.out.println(solution.possibleBipartition(4, arr));

//        int[][] arr = InputUtil.toDoubleIntegerArray(" [[1,2],[1,3],[2,3]]");
//        System.out.println(solution.possibleBipartition(3, arr));

        int[][] arr = InputUtil.toDoubleIntegerArray("[[1,2],[3,4],[5,6],[6,7],[8,9],[7,8]]");
        System.out.println(solution.possibleBipartition(10, arr));

    }

    public static void main(String[] args) throws Exception {
        LC886 an = new LC886();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
